package com.qx.cn.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.cn.model.SendDate;
import com.qx.cn.service.SendDateService;
import com.qx.cn.tool.DateForm;

@ParentPackage("netxzt")
@Namespace("/")
@InterceptorRefs({@InterceptorRef("content")})
@Results({@Result(name = "outlogin", location = "/admin!loseSession"), @Result(name = "getOutlogin", location = "/admin!otherlogin"),
    @Result(name = "index", location = "/WEB-INF/page/user/index.jsp"), @Result(name = "sendDateForm", location = "/WEB-INF/page/sendDateInfo/sendDateList.jsp")})
@Action(value = "sendDate", interceptorRefs = {@InterceptorRef("loginedCheck")})
public class SendDateAction extends BaseAction
{
    /**
     * 注释内容
     */
    private static final long serialVersionUID = 1543206792888992012L;
    
    @Autowired
    private SendDateService sendDateService;
    
    private int page;
    
    private int rows;
    
    private Integer id;
    
    private String name;
    
    /*
     * kalin 新增，取值day(日报)，all(日报+周报)
     */
    private String type;
    
    private String weekDate;
    
    private String memo;
    
    public String sendDateForm()
    {
        return "sendDateForm";
    }
    
    public String querySendDateByPage()
        throws ParseException
    {
        SendDate sdObj = new SendDate();
        sdObj.setName(name);
        sdObj.setType(type);
        List results = sendDateService.querySendDateByPage(sdObj, page, rows);
        JSONArray arrJson = new JSONArray();
        if (results.size() > 0)
        {
            for (int i = 0; i < results.size(); i++)
            {
                Object[] row = (Object[])results.get(i);
                JSONObject json = new JSONObject();
                json.put("id", row[0]);
                json.put("name", row[1]);
                String weekDate = DateForm.dateToXingQi((String)row[1]);
                if ("星期六".equals(weekDate))
                {
                    json.put("weekDate", "<span style='color:red;'>星期六</>");
                }
                else if ("星期日".equals(weekDate))
                {
                    json.put("weekDate", "<span style='color:red;'>星期日</>");
                }
                else
                {
                    json.put("weekDate", weekDate);
                }
                json.put("memo", row[3]);
                Date dateAll = DateForm.StrToDateTime((String)row[1] + " 23:59:59");
                boolean flag = new Date().before(dateAll);
                if (flag)
                {
                    json.put("status", "<span style='color:green;'>正常</span>");
                }
                else
                {
                    json.put("status", "<span style='color:red;'>过期</span>");
                }
                String type = (String)row[4];
                if ("day".equals(type))
                {
                    json.put("type", "日报");
                }
                else if ("day,week".equals(type))
                {
                    json.put("type", "<span style='color:red;'>日报、周报</span>");
                }
                arrJson.add(json);
            }
        }
        
        JSONObject object = new JSONObject();
        object.put("total", Integer.valueOf(sendDateService.queryAllSendDates(sdObj).size()));
        object.put("rows", arrJson);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String addSendDateByAuto()
        throws ParseException
    {
        boolean flag = false;
        SendDate sendDate = sendDateService.querySendDateByAuto();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        if ((sendDate != null) && (sendDate.getName() != null))
        {
            Date myDate = formatter.parse(sendDate.getName());
            Calendar c = Calendar.getInstance();
            c.setTime(myDate);
            for (int i = 0; i < 7; i++)
            {
                c.add(5, 1);
                SendDate sendDate2 = new SendDate();
                sendDate2.setName(DateFormatUtils.format(c.getTime(), "yyyy-MM-dd"));
                int index = c.get(Calendar.DAY_OF_WEEK);
                if (index != 7 && index != 1) // 跳过周六、周日
                {
                    sendDate2.setType(index == 6 ? "day,week" : "day");// 周五
                    sendDateService.saveSendDate(sendDate2);
                }
            }
            flag = true;
        }
        else
        {
            try
            {
                Date myDate = formatter.parse(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd"));
                Calendar c = Calendar.getInstance();
                c.setTime(myDate);
                for (int i = 0; i < 7; i++)
                {
                    c.add(5, 1);
                    SendDate sendDate2 = new SendDate();
                    sendDate2.setName(DateFormatUtils.format(c.getTime(), "yyyy-MM-dd"));
                    int index = c.get(Calendar.DAY_OF_WEEK);
                    if (index != 7 && index != 1) // 跳过周六、周日
                    {
                        sendDateService.saveSendDate(sendDate2);
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            flag = true;
        }
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "自动添加发送日期成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "自动添加日期失败!");
        }
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveSendDate()
        throws IOException
    {
        boolean flag = false;
        if (id != null)
        {
            SendDate upSendDate = sendDateService.loadSendDateById(id.intValue());
            upSendDate.setType(type);
            upSendDate.setMemo(memo);
            flag = sendDateService.saveSendDate(upSendDate);
        }
        else
        {
            SendDate sendDate = new SendDate();
            sendDate.setName(name);
            sendDate.setType(type);
            sendDate.setMemo(memo);
            flag = sendDateService.saveSendDate(sendDate);
        }
        
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置发送日期成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置发送日期失败!");
        }
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String checkSaveOrUpdate()
    {
        boolean flag = false;
        Integer res = 1;
        String msg = "";
        if (id != null)
        {
            SendDate sendDate = sendDateService.queryAllSendDateByDate(name, "day");
            if ((sendDate != null) && (sendDate.getId() != id))
            {
                res = 2;
                msg = "该日期已经存在，不需要重复添加";
            }
        }
        else
        {
            SendDate sendDate = sendDateService.queryAllSendDateByDate(name, "day");
            if (sendDate != null)
            {
                res = 2;
                msg = "该日期已经存在，不需要重复添加";
            }
            else
            {
                res = 1;
            }
            
        }
        
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", res);
        }
        else
        {
            object.put("result", res);
            object.put("errorMsg", msg);
        }
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String deleteSendDate()
    {
        boolean flag = sendDateService.deleteSendDate(id.intValue());
        
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "删除发送日期成功");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "删除发送日期失败");
        }
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public int getPage()
    {
        return page;
    }
    
    public void setPage(int page)
    {
        this.page = page;
    }
    
    public int getRows()
    {
        return rows;
    }
    
    public void setRows(int rows)
    {
        this.rows = rows;
    }
    
    public Integer getId()
    {
        return id;
    }
    
    public void setId(Integer id)
    {
        this.id = id;
    }
    
    public String getName()
    {
        return name;
    }
    
    public void setName(String name)
    {
        this.name = name;
    }
    
    public String getWeekDate()
    {
        return weekDate;
    }
    
    public void setWeekDate(String weekDate)
    {
        this.weekDate = weekDate;
    }
    
    public String getMemo()
    {
        return memo;
    }
    
    public void setMemo(String memo)
    {
        this.memo = memo;
    }
    
    public String getType()
    {
        return type;
    }
    
    public void setType(String type)
    {
        this.type = type;
    }
    
}